package com.wodan.zhongjinjicang.common.orm.spring;

import java.util.Set;

import org.mybatis.spring.mapper.ClassPathMapperScanner;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;

public class OrmClassPathMapperScanner extends ClassPathMapperScanner {

	private String sqlCommandExecutorRegistryBeanName;

	public OrmClassPathMapperScanner(BeanDefinitionRegistry registry) {
		super(registry);
	}

	public void setSqlCommandExecutorRegistryBeanName(String sqlCommandExecutorRegistryBeanName) {
		this.sqlCommandExecutorRegistryBeanName = sqlCommandExecutorRegistryBeanName;
	}

	/**
	 * Calls the parent search that will search and register all the candidates.
	 * Then the registered objects are post processed to set them as
	 * MapperFactoryBeans
	 */
	@Override
	public Set<BeanDefinitionHolder> doScan(String... basePackages) {
		Set<BeanDefinitionHolder> beanDefinitions = super.doScan(basePackages);

		// 生成接口对应的proxy工厂类定义
		for (BeanDefinitionHolder holder : beanDefinitions) {
			GenericBeanDefinition definition = (GenericBeanDefinition) holder.getBeanDefinition();

			// 这里将原有实现类替换成 RdsCommonDaoProxyFactoryBean
			definition.setBeanClass(RdsCommonDaoProxyFactoryBean.class);

			// 为 RdsCommonDaoProxyFactoryBean 实例赋予 sqlCommandExecutorRegistry 属性
			definition.getPropertyValues().add("sqlCommandExecutorRegistry", new RuntimeBeanReference(sqlCommandExecutorRegistryBeanName));
		}

		return beanDefinitions;
	}
}
